import React, { useState, useEffect } from "react";
import { Page, Text } from "zmp-ui";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useI18n } from "../i18n";
import { siteApi } from "../api/login";
import Navbar from "../components/navbar";

// 商家详情数据类型
interface MerchantDetailData {
  id: number;
  name: string;
  address: string;
  lng: number;
  lat: number;
  open_time: string;
  background?: string; // 背景图片URL
  graphInfo: {
    open: boolean;
    totalBanks: number;
    availableBanks: number;
    borrowableBanks: number;
    returnableBanks: number;
  };
  distanceText: string;
}

const MerchantDetail: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  
  // 从URL参数获取siteId和distance
  const siteId = searchParams.get('siteId');
  const distance = searchParams.get('distance');
  
  const [merchantData, setMerchantData] = useState<MerchantDetailData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>("");

  // 获取商家详情数据
  const fetchMerchantDetail = async () => {
    if (!siteId) {
      setError(t("merchantDetail.missingSiteId"));
      return;
    }

    setLoading(true);
    setError("");

    try {
      // 调用API获取商家详情
      const result = await siteApi.getSiteDetail(
        parseInt(siteId),
        distance ? parseFloat(distance) : undefined
      );
      
      console.log('商家详情API响应:', result);
      setMerchantData(result.data);
    } catch (err: any) {
      console.error('获取商家详情错误:', err);
      setError(err.message || t("merchantDetail.fetchFailed"));
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchMerchantDetail();
  }, [siteId, distance]);

  // 导航到该位置
  const handleNavigate = () => {
    if (merchantData) {
      // 这里可以集成地图导航功能
      console.log('导航到位置:', merchantData.name, merchantData.lng, merchantData.lat);
      // 可以调用地图API或打开外部地图应用
    }
  };

  return (
    <Page
      className="page"
      style={{
        backgroundColor: "#F5F5F7",
        padding: 0,
        minHeight: "100vh"
      }}
    >
      {/* 顶部导航栏 */}
      <div style={{ position: "sticky", top: 0, zIndex: 100 }}>
        <Navbar title={t("merchantDetail.title")} />
      </div>

      {loading ? (
        /* 加载状态 */
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            flex: 1,
            padding: "60px 20px",
            color: "#666",
          }}
        >
          <div style={{ fontSize: "48px", marginBottom: "16px" }}>⏳</div>
          <div style={{ fontSize: "16px" }}>{t("merchantDetail.loading")}</div>
        </div>
      ) : error ? (
        /* 错误状态 */
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
            flex: 1,
            padding: "60px 20px",
            color: "#666",
          }}
        >
          <div style={{ fontSize: "48px", marginBottom: "16px" }}>❌</div>
          <div style={{ fontSize: "16px", marginBottom: "8px" }}>{t("merchantDetail.loadFailed")}</div>
          <div style={{ fontSize: "14px", color: "#999", textAlign: "center" }}>{error}</div>
        </div>
      ) : merchantData ? (
        <>
          {/* 顶部图片区域 */}
          <div
            style={{
              height: "180px",
              position: "relative",
              overflow: "hidden"
            }}
          >
            {/* 背景图片 */}
            <img
              src={merchantData.background || '/src/assets/img/merchant/default.jpg'}
              alt={merchantData.name}
              style={{
                width: "100%",
                height: "100%",
                objectFit: "cover",
                position: "absolute",
                top: 0,
                left: 0
              }}
            />
            
            {/* 半透明遮罩 */}
            <div
              style={{
                position: "absolute",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: "rgba(0, 0, 0, 0.3)"
              }}
            />
            
            {/* 商家名称 */}
            <div
              style={{
                position: "absolute",
                top: "50%",
                left: "50%",
                transform: "translate(-50%, -50%)",
                zIndex: 1,
                textAlign: "center",
                color: "white"
              }}
            >
              <div
                style={{
                  fontSize: "24px",
                  fontWeight: "bold",
                  marginBottom: "8px"
                }}
              >
                {merchantData.name}
              </div>
              <div
                style={{
                  fontSize: "16px",
                  opacity: 0.9
                }}
              >
                {merchantData.distanceText}
              </div>
            </div>
          </div>

          {/* 中间信息卡片 */}
          <div
            style={{
              margin: "16px",
              marginBottom: "100px", // 为底部吸顶按钮留出空间
              backgroundColor: "white",
              borderRadius: "12px",
              padding: "20px",
              boxShadow: "0 2px 8px rgba(0,0,0,0.1)"
            }}
          >
            {/* 营业时间 */}
            <div style={{ 
              marginBottom: "12px", 
              paddingBottom: "12px",
              borderBottom: "1px solid #f0f0f0"
            }}>
              <div
                style={{
                  fontSize: "14px",
                  color: "#666",
                  marginBottom: "8px"
                }}
              >
                {t("merchantDetail.businessHours")}
              </div>
              <div
                style={{
                  fontSize: "16px",
                  fontWeight: "500",
                  color: "#333",
                  marginBottom: "4px"
                }}
              >
                {merchantData.open_time}
              </div>
              <div
                style={{
                  fontSize: "14px",
                  color: merchantData.graphInfo.open ? "#4ECDC4" : "#FF6B6B",
                  fontWeight: "500"
                }}
              >
                {merchantData.graphInfo.open ? t("merchantDetail.inService") : t("merchantDetail.closed")}
              </div>
            </div>

            {/* 充电宝状态 */}
            <div style={{ 
              marginBottom: "12px", 
              paddingBottom: "12px",
              borderBottom: "1px solid #f0f0f0"
            }}>
              <div
                style={{
                  fontSize: "14px",
                  color: "#666",
                  marginBottom: "12px"
                }}
              >
                {t("merchantDetail.powerBankStatus")}
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  marginBottom: "8px"
                }}
              >
                <span style={{ fontSize: "14px", color: "#333" }}>{t("merchantDetail.availableForRent")}:</span>
                <span style={{ fontSize: "14px", color: "#4ECDC4", fontWeight: "500" }}>
                  {merchantData.graphInfo.borrowableBanks}
                </span>
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  marginBottom: "8px"
                }}
              >
                <span style={{ fontSize: "14px", color: "#333" }}>{t("merchantDetail.availableForReturn")}:</span>
                <span style={{ fontSize: "14px", color: "#4ECDC4", fontWeight: "500" }}>
                  {merchantData.graphInfo.returnableBanks}
                </span>
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between"
                }}
              >
                <span style={{ fontSize: "14px", color: "#333" }}>{t("merchantDetail.total")}:</span>
                <span style={{ fontSize: "14px", color: "#666", fontWeight: "500" }}>
                  {merchantData.graphInfo.totalBanks}
                </span>
              </div>
            </div>

            {/* 联系电话 */}
            <div style={{ 
              marginBottom: "12px", 
              paddingBottom: "12px",
              borderBottom: "1px solid #f0f0f0"
            }}>
              <div
                style={{
                  fontSize: "14px",
                  color: "#666",
                  marginBottom: "8px"
                }}
              >
                {t("merchantDetail.contactPhone")}
              </div>
              <div
                style={{
                  fontSize: "16px",
                  color: "#333",
                  fontWeight: "500"
                }}
              >
                {merchantData.address || t("merchantDetail.noPhone")}
              </div>
            </div>

            {/* 详细地址 */}
            <div>
              <div
                style={{
                  fontSize: "14px",
                  color: "#666",
                  marginBottom: "8px"
                }}
              >
                {t("merchantDetail.detailedAddress")}
              </div>
              <div
                style={{
                  fontSize: "16px",
                  color: "#333",
                  lineHeight: "1.5"
                }}
              >
                {merchantData.address}
              </div>
            </div>
          </div>

          {/* 底部吸顶导航按钮 */}
          <div
            style={{
              position: "fixed",
              bottom: 0,
              left: 0,
              right: 0,
              padding: "16px",
              paddingBottom: "24px",
              backgroundColor: "#F5F5F7",
              borderTop: "1px solid #f0f0f0"
            }}
          >
            <button
              onClick={handleNavigate}
              style={{
                width: "100%",
                height: "52px",
                backgroundColor: "#FF6B35",
                color: "white",
                border: "none",
                borderRadius: "26px",
                fontSize: "16px",
                fontWeight: "500",
                cursor: "pointer",
                transition: "all 0.2s ease"
              }}
              onMouseDown={(e) => {
                e.currentTarget.style.backgroundColor = "#E55A2B";
              }}
              onMouseUp={(e) => {
                e.currentTarget.style.backgroundColor = "#FF6B35";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.backgroundColor = "#FF6B35";
              }}
            >
              {t("merchantDetail.goNow")} {distance ? parseFloat(distance).toFixed(2) : '0.00'}Km
            </button>
          </div>
        </>
      ) : null}
    </Page>
  );
};

export default MerchantDetail;
